package com.seed.application;

import cn.hutool.core.util.StrUtil;
import com.seed.core.enumeration.AppMode;
import com.seed.util.AppLoadKit;
import com.seed.util.ThrowKit;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.io.File;

public class SeedLoaded implements Condition  {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Environment environment = context.getEnvironment();
        Sa.setEnvironment(environment);

        String fileFullName = environment.getProperty("seed.file");
        if(StrUtil.isBlank(fileFullName)) ThrowKit.exception("请配置【seed.file】");

        File file = new File(fileFullName);
        if(!file.exists()) ThrowKit.exception("配置文件【%s】不存在", fileFullName);

        Sa.setFile(file);
        Sa.setConfiguration(AppLoadKit.load(file));

        AppMode mode = AppMode.valueOf(environment.getProperty("seed.mode", "single"));
        Sa.setMode(mode);

        if (mode == AppMode.dev) {
            String filePath = environment.getProperty("seed.path");
            if(StrUtil.isBlank(filePath)) ThrowKit.exception("请配置【seed.path】");

            File path = new File(filePath);
            if(!path.exists()) path.mkdirs();
            Sa.setPath(path);
        }

        return true;
    }
}
